package cn.zyq.ykb.controller.mgt.system;


import cn.zyq.ykb.beans.sys.SysAdmin;
import cn.zyq.ykb.beans.sys.SysAdminRole;
import cn.zyq.ykb.beans.sys.SysDept;
import cn.zyq.ykb.beans.sys.SysRole;
import cn.zyq.ykb.service.sys.SysAdminService;
import cn.zyq.ykb.service.sys.SysDeptService;
import cn.zyq.ykb.service.sys.SysPermissionService;
import cn.zyq.ykb.service.sys.SysRoleService;
import cn.zyq.ykb.system.annotation.Log;
import cn.zyq.ykb.system.common.BaseController;
import cn.zyq.ykb.system.common.PageParam;
import cn.zyq.ykb.system.exception.BusinessException;
import cn.zyq.ykb.system.ry.enums.BusinessType;
import cn.zyq.ykb.system.ry.model.LoginUser;
import cn.zyq.ykb.system.ry.security.service.TokenService;
import cn.zyq.ykb.system.ry.util.StringUtils;
import cn.zyq.ykb.system.ry.util.poi.ExcelUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 角色信息
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/mgt/system/role")
public class SysRoleController extends BaseController {
    @Autowired
    private SysRoleService roleService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private SysAdminService sysAdminService;

    @Autowired
    private SysDeptService deptService;

    @PreAuthorize("@ss.hasPermi('system:role:list')")
    @PostMapping("/list")
    public Object list(@RequestBody PageParam param) {
        return roleService.list(param, this.getLoginSysAdmin());
    }

    @Log(title = "角色管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:role:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysRole role) {
        List<SysRole> list = roleService.selectRoleList(role);
        ExcelUtil<SysRole> util = new ExcelUtil<SysRole>(SysRole.class);
        util.exportExcel(response, list, "角色数据");
    }

    /**
     * 根据角色编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:role:query')")
    @GetMapping(value = "/{roleId}")
    public Object getInfo(@PathVariable Integer roleId) {
        roleService.checkRoleDataScope(roleId);
        return roleService.selectRoleById(roleId);
    }

    /**
     * 新增角色
     */
    @PreAuthorize("@ss.hasPermi('system:role:add')")
    @Log(title = "角色管理", businessType = BusinessType.INSERT)
    @PostMapping
    public Object add(@Validated @RequestBody SysRole role) {
        if (!roleService.checkRoleNameUnique(role)) {
            throw new BusinessException("新增角色'" + role.getRoleName() + "'失败，角色名称已存在");
        } else if (!roleService.checkRoleKeyUnique(role)) {
            throw new BusinessException("新增角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        return roleService.add(role, this.getLoginSysAdmin());

    }

    /**
     * 修改保存角色
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public void edit(@Validated @RequestBody SysRole role) {
        roleService.checkRoleAllowed(role);
        roleService.checkRoleDataScope(role.getSysRoleID());
        if (!roleService.checkRoleNameUnique(role)) {
            throw new BusinessException("修改角色'" + role.getRoleName() + "'失败，角色名称已存在");
        } else if (!roleService.checkRoleKeyUnique(role)) {
            throw new BusinessException("修改角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        if (roleService.update(role, this.getLoginSysAdmin()) > 0) {
            // 更新缓存用户权限
            LoginUser loginUser = getMgtLoginUser();
            if (StringUtils.isNotNull(loginUser.getSysAdmin()) && !loginUser.getSysAdmin().isAdmin()) {
                loginUser.setPermissions(permissionService.getMenuPermission(loginUser.getSysAdmin()));
                loginUser.setSysAdmin(sysAdminService.selectUserByUserName(loginUser.getSysAdmin().getUserName()));
                tokenService.setLoginUser(loginUser);
            }
        } else {
            throw new BusinessException("修改角色'" + role.getRoleName() + "'失败，请联系管理员");
        }

    }

    /**
     * 修改保存数据权限
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping("/dataScope")
    public Object dataScope(@RequestBody SysRole role) {
        roleService.checkRoleAllowed(role);
        roleService.checkRoleDataScope(role.getSysRoleID());
        return roleService.authDataScope(role);
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public Object changeStatus(@RequestBody SysRole role) {
        roleService.checkRoleAllowed(role);
        roleService.checkRoleDataScope(role.getSysRoleID());
        return roleService.updateRoleStatus(role);
    }

    /**
     * 删除角色
     */
    @PreAuthorize("@ss.hasPermi('system:role:remove')")
    @Log(title = "角色管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{roleIds}")
    public Object remove(@PathVariable Integer[] roleIds) {
        return roleService.deleteRoleByIds(roleIds);
    }

    /**
     * 获取角色选择框列表
     */
    @PreAuthorize("@ss.hasPermi('system:role:query')")
    @GetMapping("/optionselect")
    public Object optionselect() {
        return roleService.selectRoleAll();
    }

    /**
     * 查询已分配用户角色列表
     */
    @PreAuthorize("@ss.hasPermi('system:role:list')")
    @PostMapping("/authUser/allocatedList")
    public Object allocatedList(@RequestBody PageParam param) {
        PageHelper.startPage(param.getPage(), param.getPageSize());
        List<SysAdmin> list = sysAdminService.selectAllocatedList(param);
        return new PageInfo<>(list);
    }

    /**
     * 查询未分配用户角色列表
     */
    @PreAuthorize("@ss.hasPermi('system:role:list')")
    @PostMapping("/authUser/unallocatedList")
    public Object unallocatedList(@RequestBody PageParam param) {
        PageHelper.startPage(param.getPage(), param.getPageSize());
        List<SysAdmin> list = sysAdminService.selectUnallocatedList(param);
        return new PageInfo<>(list);
    }

    /**
     * 取消授权用户
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.GRANT)
    @PutMapping("/authUser/cancel")
    public Object cancelAuthUser(@RequestBody SysAdminRole userRole) {
        return roleService.deleteAuthUser(userRole);
    }

    /**
     * 批量取消授权用户
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.GRANT)
    @PutMapping("/authUser/cancelAll")
    public Object cancelAuthUserAll(Integer roleId, Integer[] userIds) {
        return roleService.deleteAuthUsers(roleId, userIds);
    }

    /**
     * 批量选择用户授权
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.GRANT)
    @PutMapping("/authUser/selectAll")
    public Object selectAuthUserAll(Integer roleId, Integer[] userIds) {
        roleService.checkRoleDataScope(roleId);
        return roleService.insertAuthUsers(roleId, userIds);
    }

    /**
     * 获取对应角色部门树列表
     */
    @PreAuthorize("@ss.hasPermi('system:role:query')")
    @GetMapping(value = "/deptTree/{roleId}")
    public Object deptTree(@PathVariable("roleId") Integer roleId) {
        Map ajax = new HashMap();
        ajax.put("checkedKeys", deptService.selectDeptListByRoleId(roleId));
        ajax.put("depts", deptService.selectDeptTreeList(new SysDept()));
        return ajax;
    }
}
